import { defineComponent, reactive } from 'vue'
import { RouterLink, onBeforeRouteLeave } from 'vue-router'
import { Button, Input } from 'ant-design-vue'

import { get } from '@/utils/http'
import { useStore } from '@/store'
import styles from './styles.module.less'

export default defineComponent({
  name: 'Home',
  setup() {
    const state: { msg: string; topics: { id: string; title: string }[] } = reactive({ msg: 'hello', topics: [] })
    const { counter } = useStore()

    const getList = async () => {
      // http 请求
      await get('/topics').catch((res) => {
        console.log(res)
        state.topics = res.data.data
      })
    }

    // 路由跳转拦截
    onBeforeRouteLeave((to, from, next) => {
      console.log('to', to)
      next()
    })

    return () => (
      <>
        <h1>Home Page</h1>
        <ol>
          <li>
            <p>less module</p>
            <p class={styles.title}>custom title with less</p>
          </li>
          <li>
            <p>数据绑定</p>
            <p>msg: {state.msg}</p>
            <Input value={state.msg} onChange={(e) => (state.msg = e?.target?.value ?? '')} />
          </li>
          <li>
            <p>全局状态管理</p>
            <p>count from store: {counter.state.count}</p>
            <Button onClick={counter.add}>count +</Button>
          </li>
          <li>
            <p>axios 请求</p>
            <Button onClick={getList}>get Topics</Button>
            <ol>
              {state.topics.map((v) => (
                <li key={v.id}>{v.title}</li>
              ))}
            </ol>
          </li>
          <li>
            <p>路由跳转</p>
            <Button>
              <RouterLink to='/about'>goto about</RouterLink>
            </Button>
          </li>
        </ol>
      </>
    )
  },
})
